package com.sun.sangeng.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

public class OptionalDemo {

    public static void main(String[] args) {
        //Author author = getAuthor();
        //Optional<Author> author1 = Optional.ofNullable(author);
        //author1.ifPresent(author2 -> System.out.println(author2.getName()));

        //Optional<Author> optionalAuthor = getOptionalAuthor();
        //optionalAuthor.ifPresent(author -> System.out.println(author.getName()));

        //Optional<Author> optionalAuthor = getOptionalAuthor();
        //Author author = optionalAuthor.orElseGet(() -> new Author());
        //System.out.println(author.getName());

        //Optional<Author> optionalAuthor = getOptionalAuthor();
        //try {
        //    Author author = optionalAuthor.orElseThrow(() -> new RuntimeException("数据为null"));
        //} catch (Throwable e) {
        //    e.printStackTrace();
        //}
        
        //testOptionFilter();
        testOptionalMap();


    }

    private static void testOptionalMap() {
        Optional<Author> optionalAuthor = getOptionalAuthor();
        Optional<List<Book>> bookList = optionalAuthor.map(Author::getBooks);
        bookList.ifPresent(books -> System.out.println(books));
    }

    private static void testOptionFilter() {
        Optional<Author> optionalAuthor = getOptionalAuthor();
        optionalAuthor.filter(author -> author.getAge() > 8).ifPresent(author1 -> System.out.println(author1.getName()));
    }

    // 返回值修改成Optional对象
    public static Optional<Author> getOptionalAuthor() {
        Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟真理的祖安人", null);
        List<Book> books1 = new ArrayList<>();
        books1.add(new Book(1L, "刀的两侧是光明与黑暗", "哲学，爱情", 88, "用一把刀划分了爱恨"));
        author.setBooks(books1);
        //return author == null ? Optional.empty() : Optional.of(author);

        // 用这个方法比上面的更简单
        return Optional.ofNullable(author);
    }

    public static Author getAuthor() {
        Author author = new Author(1L, "蒙多", 33, "一个从菜刀中明悟真理的祖安人", null);
        return null;
    }
}
